<template>
    <div >
        <el-card shadow="hover">
            <div style="width: 700px;">
                <el-form ref="formRef" :model="formData" :rules="rules" label-width="90px">
                    <el-form-item label="账号" prop="name">
                        <el-input v-model="formData.name" disabled />
                    </el-form-item>
                    <el-form-item label="原密码" prop="oldpassword">
                        <el-input v-model="formData.oldpassword" placeholder="请输入原密码" />
                    </el-form-item>
                    <el-form-item label="新密码" prop="newpassword">
                        <el-input v-model="formData.newpassword" placeholder="请输入新密码" />
                    </el-form-item>
                </el-form>
                <div class="center">
                    <el-button type="primary" @click="onSubmit" :loading="loading">确定修改</el-button>
                </div>
            </div>
        </el-card>

    </div>
</template>

<script setup lang="ts">
import {editUserPasswordApi} from '@/api/auth/user'
import router from '@/router';
import { useUserStore } from '@/store/modules/user';
import { getPassword } from '@/utils/cache/local-storage';
import { decryptAES } from '@/utils/secret';
import { ElMessage } from 'element-plus';
import { onMounted, ref, unref } from 'vue';


onMounted(() => {
  const pswd = getPassword()
  if (pswd != null) {
    const secretText = decryptAES(pswd.toString())
    formData.value.name = secretText.split(",")[0]
  }
})

const formRef = ref<HTMLElement | null>(null);
const formData = ref({
    name: undefined,
    oldpassword: undefined,
    newpassword: undefined,
})
// 表单校验
const rules = {
    oldpassword: [{ required: true, message: '原密码不能为空', trigger: 'blur' }],
    newpassword: [{ required: true, message: '新密码不能为空', trigger: 'blur' }],
}

const loading=ref(false)
const userStore = useUserStore()
// 提交
const onSubmit = () => {
    const formWrap = unref(formRef) as any;
    if (!formWrap) return;
    formWrap.validate((valid: boolean) => {
        if (valid) {
            
            const {oldpassword,newpassword}=formData.value
            if(oldpassword==newpassword) return ElMessage.error('新密码和原密码不能一样')
            loading.value = true;
            //添加
            let obj={ oldpassword,newpassword}
            editUserPasswordApi(obj)
                .then(() => {
                    ElMessage.success('密码修改成功，即将退出重新登录');
                    setTimeout(() => {
                          userStore.logout()
                          router.push("/login")
                    }, 1500);
                })
                .finally(() => {
                    loading.value = false;
                });
        }
    });
};
</script>

<style scoped></style>
